package com.aplink.generic.widgets;

import java.util.ArrayList;
import java.util.List;

import sdt.brc.android.BarcodeReader;
import sdt.brc.android.BarcodeReaderResult;
import sdt.brc.android.BarcodeReaderUtil;
import sdt.brc.android.BarcodeScanDialog;
import sdt.brc.android.OnRecognitionListener;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.YuvImage;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.MediaColumns;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.aplink.generic.GenericApplication;
import com.aplink.generic.GenericCapturePhotoActivity;
import com.aplink.generic.GenericFragment;
import com.aplink.generic.adapter.GalleryPagerAdapter;
import com.aplink.generic.database.SqlMethods;
import com.aplink.generic.dictionary.GenericDictionary;
import com.aplink.generic.interfaces.OnActionBarSelectionListener;
import com.aplink.generic.interfaces.OnActivityResultListener;
import com.aplink.generic.interfaces.OnGetObjProInfo;
import com.aplink.generic.interfaces.OnRotateListener;
import com.aplink.generic.network.GenericFile;
import com.aplink.generic.pojo.ContentData;
import com.aplink.generic.pojo.GenericAttribute;
import com.aplink.generic.pojo.GenericObject;
import com.aplink.generic.pojo.controlspec.ControlSpec;
import com.aplink.generic.pojo.controlspec.GallerySpec;
import com.aplink.generic.util.BitmapUtis;
import com.aplink.generic.widgets.custom.Gallery;

public class ApLinkGallery extends ApLinkBaseView implements
		OnRecognitionListener, OnRotateListener, OnActivityResultListener {
	private static final int REQUEST_IMAGE_CAPTURE = 1000;
	private static int SELETE_FROM_GALLERY = 2000;
	private GenericFile fileTemp;
	private final OnActionBarSelectionListener mActionBarSelectionListener = new OnActionBarSelectionListener() {

		@Override
		public boolean onSelectionItemSelected(final int itemPosition,
				final String value, final ArrayList<String> filterField) {
			if (!filterField.isEmpty()) {
				mGalleryPagerAdapter.getFilter(filterField).filter(value);
			}
			return false;
		}
	};

	public boolean isUpload() {
		return mGallerySpec.isUpload();
	}

	private BarcodeScanDialog mCamDlg = null;
	private final ContentData mContentData;
	private View mCtrlBarcodeResult = null;
	private final ArrayList<GenericFile> mDeleteFiles;
	private final ArrayList<GenericObject> mDeleteObjects;
	private GalleryPagerAdapter mGalleryPagerAdapter;
	private final GallerySpec mGallerySpec;
	private ArrayList<GenericObject> mGenericObjects;
	private final ArrayList<GenericFile> mInsertFiles;
	private final ArrayList<GenericObject> mInsertObjects;
	private Gallery mViewPager;
	private final OnClickListener onDeleteImage = new OnClickListener() {

		@Override
		public void onClick(final View v) {
			final int selectedIndex = mViewPager.getGallery().getCurrentItem();
			final GenericObject deleteObject = mGalleryPagerAdapter
					.delete(selectedIndex);
			if (deleteObject != null) {
				mDeleteFiles.add(mGalleryPagerAdapter.getFile(deleteObject));
				mDeleteObjects.add(deleteObject);
			}
		}
	};

	private final OnClickListener onScanBarcode = new OnClickListener() {

		@Override
		public void onClick(final View v) {
			if (!TextUtils.isEmpty(mGallerySpec.getScanBarcode())) {
				mCamDlg = new BarcodeScanDialog(getActivity(),
						"Purchased License key");
				if (mCamDlg != null) {
					mCamDlg.setBarcodeTypes(BarcodeReader.SDTBARCODE_ALL_1D);
					mCamDlg.setRecognitionListener(ApLinkGallery.this);
					mCamDlg.show();
				}

				final String ctrlResultId = mGallerySpec.getBarcodeResultsID();
				if (!TextUtils.isEmpty(ctrlResultId)) {
					mCtrlBarcodeResult = ApLinkGallery.this
							.getGenericFragment()
							.getAPLinkViewByID(ctrlResultId).getView();
				}
			}
		}
	};

	private final OnClickListener onSelectFromGallery = new OnClickListener() {

		@Override
		public void onClick(final View v) {
			final Intent intent = new Intent();
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			intent.addCategory(Intent.CATEGORY_OPENABLE);
			getGenericFragment().startActivityForResult(intent,
					ApLinkGallery.SELETE_FROM_GALLERY);
		}
	};

	private final OnClickListener onTakePicture = new OnClickListener() {

		@Override
		public void onClick(final View v) {
			// final Intent takePictureIntent = new Intent(
			// MediaStore.ACTION_IMAGE_CAPTURE);
			// if (takePictureIntent.resolveActivity(ApLinkGallery.this
			// .getActivity().getPackageManager()) != null) {
			// fileTemp = BitmapUtis.getInstance().createTempFile(
			// "FILE_TEMP.TMP");
			// final File photoFile = fileTemp.getRealFile();
			// if (photoFile != null) {
			// takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
			// Uri.fromFile(photoFile));
			// getGenericFragment().startActivityForResult(
			// takePictureIntent,
			// ApLinkGallery.REQUEST_IMAGE_CAPTURE);
			// }
			// }

			Intent intent = new Intent(getApplicationContext(),
					GenericCapturePhotoActivity.class);
			getGenericFragment().startActivityForResult(intent, 11111);
		}
	};

	public ApLinkGallery(final GenericFragment genericFragment,
			final ControlSpec controlSpec, final View view, Bundle bundle) {
		super(genericFragment, controlSpec, view, bundle);
		this.mViewPager = (Gallery) view;
		this.mGallerySpec = (GallerySpec) controlSpec;
		this.mInsertObjects = new ArrayList<GenericObject>();
		this.mDeleteObjects = new ArrayList<GenericObject>();
		this.mGenericObjects = new ArrayList<GenericObject>();
		this.mDeleteFiles = new ArrayList<GenericFile>();
		this.mInsertFiles = new ArrayList<GenericFile>();
		this.mContentData = mGallerySpec.getContentData();
		if (bundle != null) {
			fileTemp = bundle.getParcelable("FILE_TEMP");
			mGenericObjects = bundle.getParcelableArrayList("LIST_OBJECT");
		}
	}

	@Override
	public void clear() {
		this.mDeleteFiles.clear();
		this.mDeleteObjects.clear();
		this.mInsertFiles.clear();
		this.mInsertObjects.clear();
	}

	public void closeScanBarcode() {
		if (this.mCamDlg != null) {
			this.mCamDlg.dismiss();
		}
	}

	public void firstPage() {
		this.mViewPager.setCurrentItem(0, true);
	}

	@Override
	public GenericAttribute getAttribute() {
		return null;
	}

	public ContentData getContentData() {
		return this.mContentData;
	}

	public ArrayList<GenericFile> getDeleteFiles() {
		return this.mDeleteFiles;
	}

	public ArrayList<GenericObject> getDeleteObjects() {
		return this.mDeleteObjects;
	}

	public ArrayList<GenericFile> getInsertFiles() {
		return this.mInsertFiles;
	}

	public ArrayList<GenericObject> getInsertObjects() {
		return this.mInsertObjects;
	}

	@Override
	public GenericDictionary<String, GenericAttribute> getListAttributes() {
		return null;
	}

	@Override
	public Gallery getView() {
		return mViewPager;
	}

	public void hideCameraDialog() {
		if (this.mCamDlg != null) {
			this.mCamDlg.dismiss();
		}
	}

	@Override
	protected void initViewProperties() {

	}

	public boolean isEmpty() {
		return mGalleryPagerAdapter.getCount() == 0;
	}

	@Override
	public void languageChanged() {

	}

	public void lastPage() {
		final int maxPage = this.mGalleryPagerAdapter.getCount();
		this.mViewPager.setCurrentItem(maxPage - 1, true);
	}

	@Override
	protected void loadBindingObject() {
		if (mGenericObjects.isEmpty()) {
			this.mGenericObjects = loadDatas();
		}
		this.mGalleryPagerAdapter = new GalleryPagerAdapter(
				this.mGenericObjects, this.mGallerySpec);
		this.mViewPager.setAdapter(this.mGalleryPagerAdapter);
		this.mViewPager.setOffscreenPageLimit(2);
	}

	private ArrayList<GenericObject> loadDatas() {
		ArrayList<GenericObject> genericObjects = new ArrayList<GenericObject>();
		if (!TextUtils.isEmpty(this.mGallerySpec.getFilterBy())) {
			final String selectWhere[] = this.mGallerySpec.getFilterBy().split(
					";");
			final SqlMethods whereClause = SqlMethods.getInstance();
			for (int i = 0; i < selectWhere.length; i++) {
				final String solumnName = selectWhere[i];
				whereClause.equal(solumnName,
						getPassedObject().getValue(solumnName));
				if (i < (selectWhere.length - 1)) {
					whereClause.and();
				}
			}
			genericObjects = getDatabaseGet().getList(this.mContentData,
					whereClause.toString());
		}
		return genericObjects;
	}

	@Override
	protected void loadDefaultObject() {
		if (this.mGallerySpec.isLoadAll()) {
			if (mGenericObjects.isEmpty()) {
				this.mGenericObjects = getDatabaseGet().getList(
						this.mContentData, null);
			}
			this.mGalleryPagerAdapter = new GalleryPagerAdapter(
					this.mGenericObjects, this.mGallerySpec);
			this.mViewPager.setAdapter(mGalleryPagerAdapter);
		} else {
			this.mGenericObjects = loadDatas();
			this.mGalleryPagerAdapter = new GalleryPagerAdapter(
					mGenericObjects, this.mGallerySpec);
			this.mViewPager.setAdapter(this.mGalleryPagerAdapter);
		}
	}

	public void nextPage() {
		final int nextPage = this.mViewPager.getCurrentItem() + 1;
		final int maxPage = this.mGalleryPagerAdapter.getCount();
		if (nextPage < maxPage) {
			this.mViewPager.setCurrentItem(nextPage, true);
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			if (requestCode == 11111) {
				GenericFile genericFile = data.getExtras().getParcelable(
						"bitmapFile");
				final GenericObject genericObject = mGalleryPagerAdapter
						.add(genericFile.getLocalPath());
				mInsertObjects.add(genericObject);
				mInsertFiles.add(genericFile);
				lastPage();
			} else if (requestCode == ApLinkGallery.REQUEST_IMAGE_CAPTURE) {
				final Bitmap bitmap = BitmapUtis.getInstance()
						.decodeSampledBitmapFromFile(fileTemp.getLocalPath(),
								mGallerySpec.getImageWidth(),
								mGallerySpec.getImageHeight());
				final GenericFile genericFile = BitmapUtis.getInstance()
						.savebitmap(
								GenericApplication.getInstance()
										.getCreatedTime(), bitmap);
				final GenericObject genericObject = mGalleryPagerAdapter
						.add(genericFile.getLocalPath());
				mInsertObjects.add(genericObject);
				mInsertFiles.add(genericFile);
				lastPage();
			} else if (requestCode == ApLinkGallery.SELETE_FROM_GALLERY) {
				final Uri pickedImage = data.getData();
				final String[] filePath = { MediaColumns.DATA };
				Cursor cursor = getActivity().getContentResolver().query(
						pickedImage, filePath, null, null, null);
				cursor.moveToFirst();
				final String imagePath = cursor.getString(cursor
						.getColumnIndex(filePath[0]));
				final Bitmap bitmap = BitmapUtis.getInstance()
						.decodeSampledBitmapFromFile(imagePath,
								mGallerySpec.getImageWidth(),
								mGallerySpec.getImageHeight());
				final GenericFile genericFile = BitmapUtis.getInstance()
						.savebitmap(
								GenericApplication.getInstance()
										.getCreatedTime(), bitmap);

				final GenericObject genericObject = mGalleryPagerAdapter
						.add(genericFile.getLocalPath());
				mInsertObjects.add(genericObject);
				mInsertFiles.add(genericFile);
				lastPage();
				cursor.close();
				cursor = null;
			}
		}
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public void onRecognitionResults(final List results, final YuvImage srcImage) {
		if (mCtrlBarcodeResult != null) {
			for (final BarcodeReaderResult barcodeReaderResult : (List<BarcodeReaderResult>) results) {
				final String barcodeValue = barcodeReaderResult.getValue();
				if (this.mCtrlBarcodeResult instanceof TextView) {
					((TextView) this.mCtrlBarcodeResult).setText(barcodeValue);
				} else if (this.mCtrlBarcodeResult instanceof EditText) {
					((EditText) this.mCtrlBarcodeResult).setText(barcodeValue);
				}
			}
		}
		this.mCamDlg.hide();
		final Bitmap bitmap = BarcodeReaderUtil.decodeImageToBitmap(srcImage);
		final GenericFile genericFile = BitmapUtis.getInstance().savebitmap(
				GenericApplication.getInstance().getCreatedTime(), bitmap);
		final GenericObject genericObject = this.mGalleryPagerAdapter
				.add(genericFile.getLocalPath());
		this.mInsertObjects.add(genericObject);
		this.mInsertFiles.add(genericFile);
		lastPage();

	}

	@Override
	public void onRotateCompleted(Bundle savedInstanceState) {

	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		outState.putParcelable("FILE_TEMP", fileTemp);
		outState.putParcelableArrayList("LIST_OBJECT",
				mGalleryPagerAdapter.getGenericObjects());
	}

	public void previousPage() {
		final int previousPage = this.mViewPager.getCurrentItem() - 1;
		if (previousPage >= 0) {
			this.mViewPager.setCurrentItem(previousPage, true);
		}
	}

	@Override
	protected void setEventListener() {
		getGenericFragment().setActivityResultListener(this);
		getGenericFragment().setOnRotateListener(this);
		mViewPager.setTakePictureClick(onTakePicture);
		mViewPager.setScanBarcodeClick(onScanBarcode);
		// mViewPager.setOpenGalleryClick(onSelectFromGallery);
		mViewPager.setDeletePictureClick(onDeleteImage);
		if (getGenericFragment().hasActionBarSelectionFor(
				this.mGallerySpec.getIDName())) {
			getGenericFragment().setActionBarSelectionListener(
					this.mActionBarSelectionListener);
		}
	}

	@Override
	public void setObjPropInfoTemp(final OnGetObjProInfo getObjProInfo) {

	}

	@Override
	public void setOnClickListener(final OnClickListener onClickListener) {

	}
}
